/**
 * @param {*} req chrome通讯参数 
 * @param {*} res chrome通讯回调函数
 */

/**
 * @method 获取用户信息
 */
async function getFactoryInfo(res) {
  if (!factoryInfo.id) {
    if (userInfo.userId && userInfo.factoryId) {
      const parseData = await requestGet(null, '/factory/merchant/factory/select_one', { id: userInfo.factoryId })
      try {
        if (JSON.parse(parseData).code === 200) {
          factoryInfo = JSON.parse(parseData).data
        }
      } catch(err) {
        let errMsg = ''
        err.code === 401 ? errMsg = '登录过期 请到商家后台刷新重试' : null
        showDataOnPage('获取云工厂信息失败', errMsg ? errMsg : err.status)
      }
    }
  }
  res(factoryInfo)
}

/**
 * @method 获取表单-类目数据
 */
function getFormData(req, res) {
  requestGet(req.origin, req.msg, req.data)
  .then(resData => {
    // 对数字精确度做处理
    const local = resData.split('"data":')[0]
    const data = resData.split('"data":')[1].replace(/\d+/g, replaceOverflow)
    const parseData = JSON.parse(local + '"data":' + data)
    res(parseData)
  })
  .catch(err => {
    let errMsg = ''
    err.code === 401 ? errMsg = '登录过期 请到商家后台刷新重试' : null
    showDataOnPage('获取表单信息失败', errMsg ? errMsg : err.status)
  })
}

/**
 * @method 将爬取的列表放到data中
 */
function pushData(req) {
  data = data.concat(req.msg.data)
}

/**
 * @method 爬取下一页列表
 */
function getNextPageInfo(req) {
  pushData(req)
  chrome.tabs.sendMessage(tabId, { action: 'setTagUrl', url: req.msg.url })
}

/**
 * @method 列表爬取完，爬取商品数据
 */
function getPageOver(req) {
  pushData(req)
  if (data.length > 0) chrome.tabs.sendMessage(tabId, { action: 'setTagUrl', url: data[currentIndex][currentSkuIndex].url })
}

/**
 * @method 查询列表是否已获取完毕，并上传商品 京东脚本以及此方法有待优化
 * @param {*} req 
 */
async function uploadDataToGYP(req) {
  showDataOnPage(`采集进度`, `商品（${currentIndex + 1} / ${data.length}） SKU（${currentSkuIndex + 1}/${data[currentIndex].length}）`)
  if (data[currentIndex].length > 1) {
    //合并sku
    if (currentSkuIndex === 0) {
      productEntity = req.msg
      productEntity.quoteMode = 'SPECIFICATIONS'
      productEntity.productSpecifications = [].concat(productEntity.productSpecifications)
      productEntity.productSourceInfo = [].concat(productEntity.productSourceInfo)
    } else {
      productEntity.productSpecifications.push(req.msg.productSpecifications)
      productEntity.productSourceInfo.push(req.msg.productSourceInfo)
    }
    if (currentSkuIndex == data[currentIndex].length - 1) {
      //上传产品
      productEntity.productSourceKey = data[currentIndex].map(v=>v.id).join('_')
      let dataResult = await replaceImageUrl(productEntity)
      dataResult.status ? setUploadData(dataResult.data) : showDataOnPage(dataResult.title, dataResult.msg)
      currentSkuIndex = 0
      //全部传完了
      if ((currentIndex + 1) === data.length) {
        finish()
      } else {
        chrome.tabs.sendMessage(tabId, { action: 'setTagUrl', url: data[++currentIndex][currentSkuIndex].url })
      }
    } else {
      //获取下一个sku
      chrome.tabs.sendMessage(tabId, { action: 'setTagUrl', url: data[currentIndex][++currentSkuIndex].url })
    }
  } else {
    //上传产品
    productEntity = req.msg
    productEntity.productSourceKey = data[currentIndex][currentSkuIndex].id
    if (!productEntity.quoteMode) {
      productEntity.quoteMode = 'NUMBERS'
      productEntity.numbersQuote = {
        inventory: req.msg.productSpecifications ? req.msg.productSpecifications.inventory : setting.inventory,
        numbersQuotes: [{
          price: req.msg.productSpecifications ? req.msg.productSpecifications.sellingPrice : '',
          startNumber: 1
        }]
      }
        delete productEntity.productSpecifications
    }
    
    productEntity.productSourceInfo = [].concat(productEntity.productSourceInfo)
    
    let dataResult = await replaceImageUrl(productEntity)
    dataResult.status ? setUploadData(dataResult.data) : showDataOnPage(dataResult.title, dataResult.msg)
    currentSkuIndex = 0
    if ((currentIndex + 1) === data.length) {
      finish()
    } else {
      chrome.tabs.sendMessage(tabId, { action: 'setTagUrl', url: data[++currentIndex][currentSkuIndex].url })
    }
  }
}

/**
 * @method 获取直卖网云工厂信息
 */
async function getGYPConfig(req, res) {
  userInfo = new Object()
  userInfo.factoryId = req.userInfo.factoryId
  userInfo.userId = req.userInfo.userId
  userInfo.username = req.userInfo.username
  userInfo.Authorization = req.userInfo.authorization
  accountPlatform = req.userInfo.platform
  uploadRequestUrl = req.origin
  if (/^http[s]{0,1}:\/\/(gyp)|(www)\.youboy\.com/.test(uploadRequestUrl)) {
    env = 'prod'
  }
  requestGet(null, '/file/config/list', { client: 2 })
  .then(response => {
    const result = JSON.parse(response)
    if (result.code === 200) {
      config = result.data
      res(accountPlatform)
    } else showDataOnPage(`获取配置信息错误`, result.msg)
  })
  .catch(err => {
    showDataOnPage(`获取配置信息错误`, err)
  })
}

/**
 * @method 验证表单之后爬取数据，如果有
 */
function gather(req) {
  reset()
  setting = req.msg
  chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
    if (tabs.length) {
      tabId = tabs[0].id
      let id = (/https:\/\/detail\.tmall\.com\/item.htm/.test(req.url) || /^https:\/\/item\.taobao\.com\/item.htm/.test(req.url))
                ? getTmallId(req.url)
                : (/https:\/\/item\.jd\.com\/(\d+)\.html/.exec(req.url) || /https:\/\/detail\.1688\.com\/offer\/(\d+)\.html/.exec(req.url))
      if (id) data.push([{ url: req.url, id: idFilter(req.url) + id[1] }])
      chrome.tabs.sendMessage(tabId, { action: 'completed', url: req.url })
    }
  })
}

/**
 * @method 爬取下一页列表
 */
function openMikecrmDetailPage(req) {
  reset()
  data = req.data
  currentIndex = 0
  chrome.tabs.create({ url: data[currentIndex].pcLoc }, function(newTab) {
    tabId = newTab.id
  })
}

function setMikecrmKeywordData(req) {
  data[currentIndex] = {...data[currentIndex], ...req.msg}
  chrome.tabs.sendMessage(tabId, { action: 'setTagUrl', url: data[currentIndex].loc })
}

function openMikecrmDetailNextPage(req) {
  data[currentIndex] = {...data[currentIndex], ...req.msg}
  // 关键词已经全部获取 上传
  if (currentIndex >= data.length - 1) {
    data.forEach(element => {
      delete element.loc
    })
    requestPost(null, '/opportunity/bmc/insert', data, function(success) {
      showDataOnPage('上传关键词', success.msg)
    })
  } else {
    currentIndex += 1
    chrome.tabs.sendMessage(tabId, { action: 'setTagUrl', url: data[currentIndex].pcLoc })
  }
}


// 将图片地址换成 上传图片接口返回的地址
async function replaceImageUrl(data) {
  var obj = {}
  if (!data) {
    return { status: false, title: '上传错误', msg: '没有数据!' }
  } else {
    // 验证表单
    let result = checkForm(data)
    let tabIdCopy = tabId
    if (result.status) {
      obj = result.data
      //获取图片总长度
      let amount = 0  
      let index = 0
      
      let details = obj.info
      let imgs = details.match(/background-image:url\((.*)\)/g)
      if (imgs) imgs = imgs.map(v => v.substring('background-image:url('.length, v.length - 1))
      //找图片
      let img_src = $('<div>'+details+'</div>').find('img')
      if (img_src.length > 0) {
        imgs = imgs || []
        img_src.each(function() {
          if ($(this).attr('src') && ($(this).attr('src').match(/\.(jpeg|jpg|gif|png)$/) !== null)) {
            imgs.push($(this).attr('src'))
          }
        })
      }

      if (imgs) amount = imgs.length
      if (obj.images) amount += obj.images.length
      if (imgs && imgs.length > 0) {
        for (let sub = 0; sub < imgs.length; sub++) {
          let v = imgs[sub]
          imgs[sub] = await baseUrlToBlob(v)
          index++
          chrome.tabs.sendMessage(tabIdCopy, { action: 'progress', data:Math.floor((index / amount) * 100) })
          details = details.replace(v, config.imageDomain + imgs[sub])
        }
      }
      delete obj.info
      obj.details = details.replace(/<a.+?>/g, '<a>')
      if (obj.images && obj.images.length > 0) {
        for (let sub = 0; sub < obj.images.length; sub++) {
          let v = obj.images[sub].imageURL
          obj.images[sub].imageURL = await baseUrlToBlob(v)
          index++
          chrome.tabs.sendMessage(tabIdCopy, { action: 'progress', data:Math.floor((index / amount) * 100) })
        }
      }
      
      // 颜色icon
      if (obj.specifications && obj.specifications.length > 0) {
        for (let sub = 0; sub < obj.specifications.length; sub++) {
          let container = obj.specifications[sub].values
          for (let item = 0; item < container.length; item++) {
            let v = container[item].icon
            if (v) v = await baseUrlToBlob(v)
          }
        }
      }
      return { status: true, data: obj }
    } else {
      noStandardsList.push(data)
      return { status: false, title: '上传错误', msg: result.msg }
    }
  }
}

function checkForm(obj) {
  var flag = { status: true, data: obj }
  if (!obj.info) return { status: false, msg: '详情缺失' } // 产品详情
  if (obj.images.length > 0) {
    for (var i in obj.images) {
      if (!obj.images[i].imageURL) return { status: false, msg: '主图路径缺失' } // 主图
    }
  } else {
    return { status: false, msg: '主图缺失' } // 主图
  }
  if (obj.productSpecifications && obj.productSpecifications.length > 0) {
    if (!obj.minQuantity || obj.minQuantity === 0) obj.minQuantity = setting.minQuantity || 1 
    obj.productSpecifications.forEach(element => {
      if (!element.inventory || Number.isNaN(parseInt(element.inventory))) {
        if (setting.inventory) {
          element.inventory = setting.inventory
        } else {
          flag = { status: false, msg: '规格库存应为整型' }
        }
      } else {
        element.inventory = parseInt(element.inventory)
        element.inventory > 1000000 ?　element.inventory = 999999 : null
      }
      if (!element.sellingPrice || Number.isNaN(parseFloat(element.sellingPrice))) {
        flag = { status: false, msg: '价格应为数字' }
      } else {
        element.sellingPrice = parseFloat(element.sellingPrice)
      }
    })
  }
  if (obj.numbersQuote) {
    if (obj.numbersQuote.numbersQuotes.length > 0) {
      if (!obj.numbersQuote.inventory || parseInt(obj.numbersQuote.inventory) === NaN) {
        if (setting.inventory) {
          obj.numbersQuote.inventory = setting.inventory
        } else {
          return { status: false, msg: '数量库存应为整型' }
        }
      } else {
        obj.numbersQuote.inventory = parseInt(obj.numbersQuote.inventory)
        obj.numbersQuote.inventory > 1000000 ?　obj.numbersQuote.inventory = 999999 : null
      }
      obj.numbersQuote.numbersQuotes.forEach(element => {
        if (!element.startNumber) element.startNumber = setting.minQuantity || 1
        if (!element.price || Number.isNaN(parseFloat(element.price))) {
          flag = { status: false, msg: '价格应为数字' }
        } else {
          element.price = parseFloat(element.price)
        }
      })
    } else {
      flag = { status: false, msg: '数量参数不能为空' }
    }
  }
  return flag
}

// 调整上传数据参数
function setUploadData(obj) {
  let query = {
    factoryId: userInfo.factoryId,
    categoryId: setting.categoryId,
    categoryName: setting.categoryName,
    sellingPoint: null,
    fareTemplateId: '1',
    ifCanSelfPick: setting.ifCanSelfPick,
    detailsUrl: config.productDetail,
    attributeValues: setting.attributeValues,
    marketTags: '',
    productStatus: 0,
    publishType: 1
  }
  query.productSourceType = obj.productSourceType || '2'
  query.fareStyle = obj.fareStyle || setting.fareStyle
  query.productUnit = unit.has(obj.productUnit)?obj.productUnit : '件'
  query.minQuantity = obj.minQuantity
  query.fareFee = obj.fareFee || setting.fareFee
  query.details = obj.details
  query.images = obj.images
  query.title = obj.title
  query.brand = obj.brand
  query.quoteMode = obj.quoteMode
  query.weight = (obj.weight && obj.weight > 0) ? obj.weight : 1
  query.productSourceKey = obj.productSourceKey
  query.productSourceInfo = JSON.stringify(obj.productSourceInfo)
  obj.specifications ? query.specifications = obj.specifications : query.specifications = []
  obj.productSpecifications ? query.productSpecifications = obj.productSpecifications : query.productSpecifications = []
  obj.numbersQuote ? query.numbersQuote = obj.numbersQuote : query.numbersQuote = null
  uploadRequest(query)
}

// 上传数据
function uploadRequest(query) {
  $.ajax({
    type: 'post',
    url: uploadRequestUrl + '/product/publish',
    headers: { ...userInfo },
    data: JSON.stringify(query),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    async: false,
    success: function (res) {
      if (res.code !== 200) {
        if (res.code === 20010001) {
          showDataOnPage('上传失败', `【${query.title}】重复`)
        }else{
          showDataOnPage('上传错误', res.msg)
        }
      } else {
        showDataOnPage('上传成功', '')
      }
    },
    error: function(err) {
      failList.push(query)
      showDataOnPage('上传失败', err.status)
    }
  })
}